import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import cache from '@/utils/cache'
import { TOKEN_KEY } from '@/enums/cacheEnums'

export interface UserState {
    token: string
    userInfo: Record<string, any>
    routes: RouteRecordRaw[]
    perms: string[]
}

const useUserStore = defineStore('user', {
    // 存储数据
    state: (): UserState => ({
        // token
        token: '',
        // 用户信息
        userInfo: {},
        // 路由
        routes: [],
        // 权限
        perms: []
    }),
    // 处理异步|逻辑
    actions: {
        resetState() {
            this.token = ''
            this.userInfo = {}
            this.perms = []
        },
        async login(data: any) {
            //登录请求
            let result: any = await reqLogin(data);
            console.log(result)
            //登录请求:成功200->token 
            //登录请求:失败201->登录失败错误的信息
            if (result.code == 200) {
                //pinia仓库存储一下token
                //由于pinia|vuex存储数据其实利用js对象
                this.token = (result.data as string);
                //本地存储持久化存储一份
                cache.set(TOKEN_KEY, result.data)
                //能保证当前async函数返回一个成功的promise
                return 'ok';
            } else {
                return Promise.reject(new Error(result.data));
            }
        }
    },
    getters: {},
})

export default useUserStore